<template>
  <div class="container">
    <!-- 标题区域 -->
    <div class="header">
      <span class="title">化学方程式配平器</span>
      <span class="subtitle">输入化学方程式，自动配平</span>
    </div>

    <!-- 输入区域 -->
    <div class="input-section">
      <div class="input-label">
        <span>输入化学方程式</span>
        <span class="example">(例: Fe2O3 + H2SO4 = Fe2(SO4)3 + H2O)</span>
      </div>
      <textarea 
        v-model="inputEquation"
        class="equation-input"
        placeholder="请输入化学方程式..."
        maxlength="500"
      ></textarea>
      
      <!-- 快捷输入按钮 -->
      <div class="quick-buttons">
        <button 
          v-for="(example, index) in exampleEquations" 
          :key="index"
          class="quick-btn"
          @click="selectExample(example.equation)"
        >
          {{ example.name }}
        </button>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <button class="balance-btn" @click="balanceEquation" :disabled="loading">
        {{ loading ? '配平中...' : '开始配平' }}
      </button>
      <button class="clear-btn" @click="clearInput">清除</button>
    </div>

    <!-- 结果显示区域 -->
    <div class="result-section" v-if="result.show">
      <div class="result-header">
        <span class="result-title">配平结果</span>
        <div :class="['result-status', result.success ? 'success' : 'error']">
          {{ result.success ? '✓ 配平成功' : '✗ 配平失败' }}
        </div>
      </div>
      
      <div class="result-content">
        <div class="result-item" v-if="result.success && result.equation">
          <span class="label">配平后的方程式：</span>
          <span class="equation-result">{{ result.equation }}</span>
        </div>
        
        <div class="result-item" v-if="result.message">
          <span class="message" :class="result.success ? 'success-msg' : 'error-msg'">
            {{ result.message }}
          </span>
        </div>
        
        <!-- 元素平衡验证 -->
        <div class="balance-check" v-if="result.success && elementBalance.length > 0">
          <span class="label">元素平衡验证：</span>
          <div class="element-list">
            <div 
              v-for="(element, index) in elementBalance" 
              :key="index"
              class="element-item"
            >
              <span class="element-symbol">{{ element.element }}</span>
              <span class="element-count">{{ element.leftCount }} = {{ element.rightCount }}</span>
              <span class="check-mark">✓</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 帮助说明 -->
    <div class="help-section">
      <span class="help-title">使用说明</span>
      <div class="help-content">
        <span class="help-item">• 支持复杂分子式，如 Fe2(SO4)3</span>
        <span class="help-item">• 使用 = 或 → 分隔反应物和生成物</span>
        <span class="help-item">• 多个化合物用 + 连接</span>
        <span class="help-item">• 点击示例快速输入</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ChemicalParser } from '../../src/utils/parser'
import { Equation } from '../../src/utils/equation'
import { BalanceChecker } from '../../src/utils/balance-checker'
import type { BalanceResult } from '../../src/types/chemistry'

// 简单的提示函数
const showToast = (title: string) => {
  console.log(title)
  alert(title)
}

// 响应式数据
const inputEquation = ref('')
const loading = ref(false)

const result = reactive({
  show: false,
  success: false,
  equation: '',
  message: '',
  leftCoeffs: [] as number[],
  rightCoeffs: [] as number[]
})

const elementBalance = ref<Array<{ element: string, leftCount: number, rightCount: number }>>([])

// 示例方程式
const exampleEquations = [
  { name: '铁锈反应', equation: 'Fe2O3 + H2SO4 = Fe2(SO4)3 + H2O' },
  { name: '燃烧反应', equation: 'C2H6 + O2 = CO2 + H2O' },
  { name: '中和反应', equation: 'HCl + NaOH = NaCl + H2O' },
  { name: '分解反应', equation: 'KClO3 = KCl + O2' },
  { name: '置换反应', equation: 'Zn + H2SO4 = ZnSO4 + H2' }
]

// 选择示例方程式
const selectExample = (equation: string) => {
  inputEquation.value = equation
  result.show = false
}

// 清除输入
const clearInput = () => {
  inputEquation.value = ''
  result.show = false
  elementBalance.value = []
}

// 配平方程式
const balanceEquation = async () => {
  if (!inputEquation.value.trim()) {
    showToast('请输入化学方程式')
    return
  }

  loading.value = true
  result.show = false

  try {
    // 解析方程式
    const equation = ChemicalParser.parseEquation(inputEquation.value)
    
    if (!equation) {
      throw new Error('方程式格式错误，请检查输入')
    }

    // 执行配平
    const balanceResult = equation.getBalanceResult()
    
    // 更新结果
    result.success = balanceResult.success
    result.equation = balanceResult.equation || ''
    result.message = balanceResult.message || ''
    result.leftCoeffs = balanceResult.leftCoeffs || []
    result.rightCoeffs = balanceResult.rightCoeffs || []
    result.show = true

    // 如果配平成功，计算元素平衡
    if (balanceResult.success && equation) {
      calculateElementBalance(equation)
    }

    // 显示结果提示
    showToast(balanceResult.success ? '配平成功！' : '配平失败')

  } catch (error) {
    console.error('配平失败:', error)
    
    result.success = false
    result.message = error instanceof Error ? error.message : '未知错误'
    result.show = true

    showToast('配平失败')
  } finally {
    loading.value = false
  }
}

// 计算元素平衡
const calculateElementBalance = (equation: Equation) => {
  try {
    const equationStr = equation.print()
    const [leftSide, rightSide] = equationStr.split(' = ')
    
    if (!leftSide || !rightSide) {
      console.error('方程式格式错误')
      return
    }

    // 提取所有元素
    const elements = BalanceChecker.extractElementsFromString(equationStr)
    
    const balance: Array<{ element: string, leftCount: number, rightCount: number }> = []
    
    for (const element of elements) {
      const leftCount = BalanceChecker.countElementInCompounds(leftSide, element)
      const rightCount = BalanceChecker.countElementInCompounds(rightSide, element)
      
      balance.push({
        element,
        leftCount,
        rightCount
      })
    }

    elementBalance.value = balance
  } catch (error) {
    console.error('计算元素平衡失败:', error)
  }
}
</script>

<style lang="scss">
.container {
  padding: 40rpx;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 60rpx;
  
  .title {
    display: block;
    font-size: 48rpx;
    font-weight: bold;
    color: #2c3e50;
    margin-bottom: 20rpx;
  }
  
  .subtitle {
    display: block;
    font-size: 28rpx;
    color: #7f8c8d;
  }
}

.input-section {
  margin-bottom: 40rpx;
  
  .input-label {
    margin-bottom: 20rpx;
    
    text {
      display: block;
      font-size: 32rpx;
      color: #2c3e50;
      margin-bottom: 10rpx;
    }
    
    .example {
      font-size: 24rpx;
      color: #7f8c8d;
    }
  }
  
  .equation-input {
    width: 100%;
    min-height: 120rpx;
    padding: 30rpx;
    border: 2rpx solid #e0e0e0;
    border-radius: 16rpx;
    font-size: 32rpx;
    line-height: 1.5;
    background-color: white;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
    
    &:focus {
      border-color: #4CAF50;
      outline: none;
    }
  }
  
  .quick-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
    margin-top: 30rpx;
    
    .quick-btn {
      padding: 16rpx 24rpx;
      font-size: 24rpx;
      background-color: #e3f2fd;
      color: #1976d2;
      border: none;
      border-radius: 20rpx;
      
      &:active {
        background-color: #bbdefb;
      }
    }
  }
}

.action-buttons {
  display: flex;
  gap: 30rpx;
  margin-bottom: 40rpx;
  
  button {
    flex: 1;
    height: 88rpx;
    border-radius: 24rpx;
    font-size: 32rpx;
    font-weight: 500;
    border: none;
    
    &:active {
      opacity: 0.8;
    }
    
    &:disabled {
      opacity: 0.6;
    }
  }
  
  .balance-btn {
    background-color: #4CAF50;
    color: white;
    box-shadow: 0 6rpx 16rpx rgba(76, 175, 80, 0.3);
  }
  
  .clear-btn {
    background-color: #f5f5f5;
    color: #666;
    border: 2rpx solid #e0e0e0;
  }
}

.result-section {
  background-color: white;
  border-radius: 20rpx;
  padding: 40rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.1);
  
  .result-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    
    .result-title {
      font-size: 36rpx;
      font-weight: bold;
      color: #2c3e50;
    }
    
    .result-status {
      padding: 12rpx 24rpx;
      border-radius: 20rpx;
      font-size: 24rpx;
      font-weight: 500;
      
      &.success {
        background-color: #e8f5e8;
        color: #4CAF50;
      }
      
      &.error {
        background-color: #ffebee;
        color: #f44336;
      }
    }
  }
  
  .result-content {
    .result-item {
      margin-bottom: 30rpx;
      
      .label {
        display: block;
        font-size: 28rpx;
        color: #666;
        margin-bottom: 15rpx;
      }
      
      .equation-result {
        display: block;
        font-size: 36rpx;
        font-weight: 500;
        color: #2c3e50;
        background-color: #f8f9fa;
        padding: 20rpx;
        border-radius: 12rpx;
        border-left: 6rpx solid #4CAF50;
      }
      
      .message {
        display: block;
        font-size: 30rpx;
        padding: 20rpx;
        border-radius: 12rpx;
        
        &.success-msg {
          color: #4CAF50;
          background-color: #e8f5e8;
        }
        
        &.error-msg {
          color: #f44336;
          background-color: #ffebee;
        }
      }
    }
    
    .balance-check {
      .element-list {
        display: flex;
        flex-wrap: wrap;
        gap: 20rpx;
        margin-top: 20rpx;
        
        .element-item {
          display: flex;
          align-items: center;
          gap: 12rpx;
          padding: 16rpx 24rpx;
          background-color: #e8f5e8;
          border-radius: 20rpx;
          
          .element-symbol {
            font-weight: bold;
            color: #2c3e50;
            font-size: 28rpx;
          }
          
          .element-count {
            color: #666;
            font-size: 24rpx;
          }
          
          .check-mark {
            color: #4CAF50;
            font-weight: bold;
            font-size: 24rpx;
          }
        }
      }
    }
  }
}

.help-section {
  background-color: white;
  border-radius: 20rpx;
  padding: 40rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .help-title {
    display: block;
    font-size: 32rpx;
    font-weight: bold;
    color: #2c3e50;
    margin-bottom: 30rpx;
  }
  
  .help-content {
    .help-item {
      display: block;
      font-size: 28rpx;
      color: #666;
      line-height: 1.8;
      margin-bottom: 16rpx;
    }
  }
}
</style>